import Vue from 'vue'

// 生成随机数 --- 永不重复
export function createRandomId () {
  return (Math.random() * 10).toString().substr(2, 5) + '-' + Math.random().toString().substr(2, 5) + '-' + (new Date()).getTime()
}

// 获取时间
export function timeStamp () {
  const date = new Date()

  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  let hour = date.getHours()
  let minute = date.getMinutes()
  let second = date.getSeconds()

  return year + '-' + (month > 10 ? month : '0' + month) + '-' + (day > 10 ? day : '0' + day) + ' ' + (hour > 10 ? hour : '0' + hour) + ':' + (minute > 10 ? minute : '0' + minute) + ':' + (second > 10 ? second : '0' + second)
}

// 深拷贝
export function deepClone (value) {
  let valueType = Array.isArray(value) ? [] : {}
  if (value && typeof value === 'object') {
    for (let key in value) {
      if (value.hasOwnProperty(key)) {
        if (value[key] && typeof value[key] === 'object') {
          // 递归
          valueType[key] = deepClone(value[key])
        } else {
          // 如果不是，简单复制
          valueType[key] = value[key]
        }
      }
    }
  }
  return valueType
}

// blob下载文件流
Vue.prototype.blobFile = function (res = {}, name) {
  // 处理文件流 转化二进制
  let blob = new Blob([res])
  // 下载文件名称
  let fileName = `${name}.xlsx`
  // 创建a标签
  let link = document.createElement('a')
  link.download = fileName
  link.style.display = 'none'
  link.href = URL.createObjectURL(blob)
  document.body.appendChild(link)
  link.click()
  URL.revokeObjectURL(link.href) // 释放URL 对象
  document.body.removeChild(link)
}

// location直接下载文件
Vue.prototype.locateFile = url => { window.location.href = `${url}` }

// 从数组中删除某个元素
Vue.prototype.removeElem = function (arr, item) {
  if (arr.length) {
    let index = arr.indexOf(item)
    if (index > -1) {
      return arr.splice(index, 1)
    }
  }
}

// ESLint babel版本过高
// export const getRouter = (path, name) => () => import(`@/${path}/${name}`)

// 路由配置函数
export const getRouter = (path, name) => () => import('@/' + path + '/' + name)

// 初始化form表单
Vue.prototype.initForm = function (form, except = false) {
  for (let key in form) {
    if (except === false || !except.includes(key)) {
      form[key] = ''
    }
  }
  return form
}

Vue.prototype.formatMoney = function (value, type, unit = '') {
  if (isNaN(value) && Object.prototype.toString.call(value) === '[object String]') {
    return value
  }
  let divisor = 100 // 元
  switch (type) {
    case 'yuan':
      break
    case 'wan':
      divisor = 1000000
      break
  }

  value = value / divisor

  return value.toFixed(2) + unit
}

// 同步form值 用于修改回显
Vue.prototype.assignForm = function (form, data) {
  for (let key in form) {
    let newKey = 'nns_' + key
    form[key] = data[newKey]
  }
  return form
}

// 用于api转换方法
export const apiTypeChange = api => {
  if (api && typeof api === 'string') {
    // eslint-disable-next-line no-eval
    return eval(api)
  }
  return api
}
